package com.ahnu.tongue.service.impl;

import com.ahnu.tongue.common.BusinessException;
import com.ahnu.tongue.dao.TongueRecordMapper;
import com.ahnu.tongue.dto.TongueAnalysisRequest;
import com.ahnu.tongue.dto.TongueAnalysisResponse;
import com.ahnu.tongue.entity.TongueRecord;
import com.ahnu.tongue.service.AIService;
import com.ahnu.tongue.service.TongueService;
import com.ahnu.tongue.utils.FileUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class TongueServiceImpl implements TongueService {

    private final TongueRecordMapper tongueRecordMapper;
    private final FileUtils fileUtils;
    private final AIService aiService;

    @Override
    @Transactional
    public TongueAnalysisResponse analyzeImage(TongueAnalysisRequest request) {
        // 1. 验证请求参数
        MultipartFile image = request.getImage();
        if (image == null || image.isEmpty()) {
            throw new BusinessException("请选择要上传的图片");
        }
        
        String contentType = image.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new BusinessException("只支持图片文件上传");
        }

        // 2. 上传图片
        String imageUrl = fileUtils.uploadImage(image);
        if (!StringUtils.hasText(imageUrl)) {
            throw new BusinessException("图片上传失败");
        }

        try {
            // 3. 调用AI模型分析图片
            File imageFile = new File(fileUtils.getAbsolutePath(imageUrl));
            Map<String, String> analysisResult = aiService.analyzeTongueImage(imageFile);

            // 4. 生成诊断文本
            String diagnosis = String.format("舌象分析结果：舌色%s，舌苔%s，舌形%s，舌润度%s",
                    analysisResult.get("color"),
                    analysisResult.get("coating"),
                    analysisResult.get("shape"),
                    analysisResult.get("moisture"));

            // 5. 生成健康建议
            String suggestion = aiService.generateHealthSuggestion(diagnosis);

            // 6. 保存记录
            TongueRecord record = new TongueRecord();
            record.setUserId(request.getUserId());
            record.setImageUrl(imageUrl);
            record.setDiagnosis(diagnosis);
            record.setColor(analysisResult.get("color"));
            record.setCoating(analysisResult.get("coating"));
            record.setShape(analysisResult.get("shape"));
            record.setMoisture(analysisResult.get("moisture"));
            record.setSuggestion(suggestion);
            record.setRemark(request.getRemark());
            record.setStatus(0);

            tongueRecordMapper.insert(record);

            // 7. 返回结果
            TongueAnalysisResponse response = new TongueAnalysisResponse();
            BeanUtils.copyProperties(record, response);
            return response;
        } catch (Exception e) {
            // 发生异常时删除已上传的图片
            fileUtils.deleteImage(imageUrl);
            throw e;
        }
    }

    @Override
    public TongueAnalysisResponse getAnalysisResult(Long recordId, Long userId) {
        if (recordId == null || userId == null) {
            throw new BusinessException("参数不能为空");
        }

        TongueRecord record = tongueRecordMapper.findById(recordId);
        if (record == null || !record.getUserId().equals(userId)) {
            throw new BusinessException("记录不存在或无权访问");
        }

        TongueAnalysisResponse response = new TongueAnalysisResponse();
        BeanUtils.copyProperties(record, response);
        return response;
    }

    @Override
    public List<TongueAnalysisResponse> getHistoryRecords(Long userId, int page, int size) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (page < 1) {
            page = 1;
        }
        if (size < 1) {
            size = 10;
        }

        int offset = (page - 1) * size;
        List<TongueRecord> records = tongueRecordMapper.findByUserIdWithPaging(userId, offset, size);
        
        return records.stream()
                .map(record -> {
                    TongueAnalysisResponse response = new TongueAnalysisResponse();
                    BeanUtils.copyProperties(record, response);
                    return response;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void deleteRecord(Long recordId, Long userId) {
        if (recordId == null || userId == null) {
            throw new BusinessException("参数不能为空");
        }

        TongueRecord record = tongueRecordMapper.findById(recordId);
        if (record == null || !record.getUserId().equals(userId)) {
            throw new BusinessException("记录不存在或无权访问");
        }

        // 删除记录和关联的图片
        tongueRecordMapper.delete(recordId);
        fileUtils.deleteImage(record.getImageUrl());
    }
} 